package edu.gatech.oops.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Validate, which tries to determine if the 
 * input in the Login Screen is correct, and acts according to whether it is a valid
 * login, and what kind of user the person who just logged in is.
 */
public class Validate extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Validate() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String username = (String)request.getParameter("username");
		String password = (String)request.getParameter("password");
		if(username.equalsIgnoreCase("Admin") && password.equals("admin123"))
			response.sendRedirect("AdminHome.jsp");
		
		else
		{
			String[] result = LoginHelper.login(username, password);
			if(result != null)
			{	
				String type = result[4];
				if(type.equals("Student"))
				{
					Student student = new Student(result[0], result[1], result[2], result[3]);
					response.sendRedirect("StudentHome.jsp");
					
				}
				else if(type.equals("Instructor"))
				{
					Instructor instructor = new Instructor(result[0], result[1], result[2], result[3]);
					response.sendRedirect("InstructorHome.jsp");
				}
				else if(type.equals("Admin"))
				{
					Admin admin = new Admin(result[0], result[1], result[2], result[3]);
					response.sendRedirect("AdminHome.jsp");
				}
			}
			else
			{
				response.sendRedirect("BadLogin.jsp");
			}
		}
			
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
